package edu.nf.homework.container;

import edu.nf.homework.annotation.Component;
import edu.nf.homework.util.ScanUtils;
import io.github.classgraph.ClassInfo;
import io.github.classgraph.ClassInfoList;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author CSY
 * @date 2025 - 04 - 16
 *
 */
public class PaymentFactory {
    private final Map<String,Object> container = new HashMap<String,Object>();

    public PaymentFactory(String packageName){
        init(packageName);
    }

    private void init(String packageName){
        ClassInfoList list = ScanUtils.scan(packageName);
        for (ClassInfo classInfo : list) {
            Class<?> clazz = classInfo.loadClass();
            if (clazz.isAnnotationPresent(Component.class)) {
                try {
                    String name = clazz.getAnnotation(Component.class).value();
                    Object instance = clazz.getConstructor().newInstance();
                    container.put(name,instance);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    public <T> T createPayment(String type){
        if (container.containsKey(type)){
            return (T)container.get(type);
        }
        throw new RuntimeException(type+" not found");
    }
}
